package cn.com.anypay.manager.controller.sdk;

import cn.com.anypay.manager.service.OcrService;
import cn.com.anysdk.ocr.exception.OcrException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/ocr")
public class OcrController {

    @Resource
    private OcrService ocrService;

    @GetMapping("/config")
    public ResponseEntity<?> getConfig() {
        try {
            Map<String, Object> config = ocrService.getCurrentConfig();
            return ResponseEntity.ok(config);
        } catch (OcrException e) {
            log.error("获取OCR配置失败", e);
            return ResponseEntity.status(500).body(Map.of(
                "success", false,
                "message", e.getMessage()
            ));
        } catch (Exception e) {
            log.error("获取OCR配置时发生未知错误", e);
            return ResponseEntity.status(500).body(Map.of(
                "success", false,
                "message", "服务器内部错误: " + e.getMessage()
            ));
        }
    }

    @PostMapping("/switch")
    public ResponseEntity<?> switchProvider(@RequestBody Map<String, Object> config) {
        try {
            String result = ocrService.switchProvider(config);
            return ResponseEntity.ok(result);
        } catch (OcrException e) {
            log.error("切换OCR服务商失败", e);
            return ResponseEntity.status(500).body(Map.of(
                "success", false,
                "message", e.getMessage()
            ));
        } catch (Exception e) {
            log.error("切换OCR服务商时发生未知错误", e);
            return ResponseEntity.status(500).body(Map.of(
                "success", false,
                "message", "服务器内部错误: " + e.getMessage()
            ));
        }
    }

    @PostMapping("/recognize")
    public ResponseEntity<?> recognize(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "serviceType", defaultValue = "general") String serviceType) {
        if (file == null || file.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "请选择要上传的文件"
            ));
        }

        try {
            var result = ocrService.recognize(file, serviceType);
            return ResponseEntity.ok(result);
        } catch (OcrException e) {
            log.error("OCR识别失败", e);
            return ResponseEntity.status(500).body(Map.of(
                "success", false,
                "message", e.getMessage()
            ));
        } catch (Exception e) {
            log.error("OCR识别时发生未知错误", e);
            return ResponseEntity.status(500).body(Map.of(
                "success", false,
                "message", "服务器内部错误: " + e.getMessage()
            ));
        }
    }
}
